package com.jx.mlxg.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jx.mlxg.common.BusinessException;
import com.jx.mlxg.entity.*;
import com.jx.mlxg.mapper.*;
import com.jx.mlxg.utils.HttpClientUtil;
import com.jx.mlxg.utils.JDUtil;
import com.jx.mlxg.utils.ResponseResult;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/jd")
public class JDController {

    @Resource
    private ShippingInfoMapper shippingInfoMapper;
    @Resource
    private AddressesMapper addressesMapper;
    @Resource
    private OrderDetailsMapper  orderDetailsMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Value("${wxpay.app-id}")
    private String appId;
    @Value("${wxpay.appSecret}")
    private String appSecret;


    @PostMapping("/orders/batchCreate")
    public ResponseResult<Object> batchInsert(@RequestBody Map<String, Object> infoMap) throws Exception {
        log.info("batchCreate--->{}", JSON.toJSONString(infoMap));
        try {
        log.info("批量发货111");
                 log.info("批量发货111");
            @SuppressWarnings("unchecked")
            List<String> orderIds = (List<String>) infoMap.get("orderIds");
            String remark = infoMap.get("remark").toString();
            if (orderIds == null || orderIds.isEmpty()) {
                return ResponseResult.failure("订单ID列表不能为空");
            }
 log.info("批量发货2");
            for (String orderId : orderIds) {
                // 查询ShippingInfo
                ShippingInfo shippingInfo = shippingInfoMapper.selectOne(new QueryWrapper<ShippingInfo>().eq("order_id", orderId));
                Orders orders = ordersMapper.selectByOrderId(orderId);
                if (shippingInfo == null) {
                    return ResponseResult.failure("未找到订单ID为 " + orderId + " 的ShippingInfo信息");
                }
 log.info("批量发货3");
                // 查询地址信息
                Addresses addresses = addressesMapper.selectById(shippingInfo.getAddressId());
                if (addresses == null) {
                    return ResponseResult.failure("未找到订单ID为 " + orderId + " 的地址信息");
                }

                // 构建收货地址
                String address = addresses.getProvince() + addresses.getCity() + addresses.getArea() + addresses.getHouseNumber();
                String name = addresses.getName();
                String phoneNumber = addresses.getPhoneNumber();

                // 查询订单详情
                List<OrderDetails> orderDetailsList = orderDetailsMapper.selectList(new QueryWrapper<OrderDetails>().eq("order_id", orderId));
                if (orderDetailsList == null || orderDetailsList.isEmpty()) {
                    return ResponseResult.failure("订单ID为 " + orderId + " 的订单详情为空");
                }

                // 构建商品名称字符串
                StringBuilder productNameBuilder = new StringBuilder();
                boolean productNotFound = false;
                for (OrderDetails orderDetails : orderDetailsList) {
                    Product product = productMapper.selectById(orderDetails.getProductId());
                    if (product == null) {
                        productNotFound = true;
                        break;
                    }
                    Integer productId = product.getProductId();
                    String productName = "";
                    switch (productId) {
                        case 13:
                            productName = "辅料";
                            break;
                        case 14:
                            productName = "烫";
                            break;
                        case 15:
                            productName = "锅";
                            break;
                        case 16:
                            productName = "体";
                            break;
                        case 17:
                            productName = "拌";
                            break;
                        case 18:
                            productName = "牛";
                            break;
                        default:
                            break;
                    }
                    productNameBuilder.append(orderDetails.getQuantity()).append(productName);
                }

                if (productNotFound) {
                    return ResponseResult.failure("未找到产品ID为 " + orderDetailsList.get(orderDetailsList.size() - 1).getProductId() + " 的产品信息");
                }
 log.info("批量发货4");
                // 计算总数量
                int totalQuantity = orderDetailsList.stream()
                        .mapToInt(OrderDetails::getQuantity)
                        .sum();
                String productName = productNameBuilder.toString();

//                // 调用京东下单接口
                HashMap<Object, Object> map = new HashMap<>();
                map.put("orderId", orderId);
                map.put("address", address);
                map.put("name", name);
                map.put("phoneNumber", phoneNumber);
                map.put("productName", productName);
                map.put("quantity", totalQuantity);
                map.put("remark",remark);
                log.info("map--->{}", JSON.toJSONString(map));
                Map resultMap = JDUtil.JDCreateOrder(map);
                log.info("resultMap---->{}",resultMap);
                String waybillCode = resultMap.get("waybillCode").toString();
                if ("0".equals(resultMap.get("code"))) {

                    log.info("批量发货5");
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("grant_type","client_credential");
                    hashMap.put("appid",appId);
                    hashMap.put("secret",appSecret);

                    String doGetJson = HttpClientUtil.doGet("https://api.weixin.qq.com/cgi-bin/token", hashMap);
                    JSONObject jsonObject = JSON.parseObject(doGetJson);
                    // 从JSONObject中获取openid并返回
                    String accessToken = jsonObject.getString("access_token");
                    log.info("accessToken--->{}",accessToken);

                    // 创建 HashMap 来构建 JSON 数据
                    Map<String, Object> wxmap = new HashMap<>();

                    // 构建 order_key
                    Map<String, Object> orderKey = new HashMap<>();
                    orderKey.put("order_number_type", 1);
                    orderKey.put("mchid", "1725596634");
                    orderKey.put("transaction_id", orders.getOrderId());
                    orderKey.put("out_trade_no", orders.getOrderId());
                    wxmap.put("order_key", orderKey);

                    // 设置 delivery_mode 和 logistics_type
                    wxmap.put("delivery_mode", 1);
                    wxmap.put("logistics_type", 1);

                    // 构建 shipping_list
                    List<Map<String, Object>> shippingList = new ArrayList<>();
                    Map<String, Object> shippingItem = new HashMap<>();
                    shippingItem.put("tracking_no", waybillCode);
                    shippingItem.put("express_company", "JD");
                    shippingItem.put("item_desc", productNameBuilder);

                    // 构建 contact
                    Map<String, Object> contact = new HashMap<>();
                    contact.put("consignor_contact", "+86-177****1234");
                    shippingItem.put("contact", contact);

                    shippingList.add(shippingItem);
                    wxmap.put("shipping_list", shippingList);

                    // 设置 upload_time 和 payer
                    ZonedDateTime now = ZonedDateTime.now(); // 获取当前时间
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); // 定义格式
                    String formattedDateTime = now.format(formatter); // 格式化时间

                    wxmap.put("upload_time", formattedDateTime);

                    Map<String, Object> payer = new HashMap<>();
                    payer.put("openid", orders.getOpenid());
                    wxmap.put("payer", payer);
                    log.info("微信提交发货信息前map--->{}", wxmap);
                    String doPostJson = HttpClientUtil.doPost("https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info", wxmap,accessToken);
                    JSONObject jsonPost = JSON.parseObject(doPostJson);
                    log.info("jsonPost--->{}", jsonPost);
                    // 从JSONObject中获取openid并返回
                    String errorCode = jsonPost.getString("errcode");
                    if(errorCode.equals("0")){
                        ordersMapper.update(new UpdateWrapper<Orders>()
                                .set("status", "已发货").set("tracking_number", waybillCode).set("shipped_date", LocalDateTime.now())
                                .eq("order_id", orderId));
                        shippingInfoMapper.update(new UpdateWrapper<ShippingInfo>()
                                .set("tracking_number", waybillCode)
                                .set("shipping_status","已发货")
                                .set("remark",remark)
                                .eq("order_id", orderId));
//                        return ResponseResult.success(true);
                    }else{
                        return ResponseResult.failure(jsonPost.getString("errmsg"));
                    }
                }else {
                    return ResponseResult.failure("下单失败，错误代码：" +/* resultMap.get("code")*/"");
                }
            }

            return ResponseResult.success(true);

        } catch (BusinessException e) {
            return ResponseResult.failure(e.getCode(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.failure("系统错误");
        }
    }

    @PostMapping("/getWaybillToken")
    public ResponseResult<Object> getAccessToken(@RequestBody Map orderMap){
        try{
            Map<String, String> map1 = new HashMap<>();
            map1.put("grant_type","client_credential");
            map1.put("appid",appId);
            map1.put("secret",appSecret);
            String doGet = HttpClientUtil.doGet("https://api.weixin.qq.com/cgi-bin/token", map1);
            JSONObject jsonObject = JSON.parseObject(doGet);
            // 从JSONObject中获取openid并返回
            String accessToken = jsonObject.getString("access_token");
            log.info("accessToken--->{}",accessToken);


            String orderId = (String) orderMap.get("orderId");
            String openId = SecurityContextHolder.getContext().getAuthentication().getName();
//            Orders order = ordersService.getOrderById(orderId, openId);
            ShippingInfo shippingInfo = shippingInfoMapper.selectOne(new QueryWrapper<ShippingInfo>().eq("order_id", orderId));
            String trackingNumber = shippingInfo.getTrackingNumber();//快递单号
            String phoneNumber = shippingInfo.getPhoneNumber();//收件号码
            HashMap<String, Object> map = new HashMap<>();
            map.put("openid",openId);
            map.put("waybill_id",trackingNumber);
            map.put("sender_phone","18822699607");
            map.put("receiver_phone",phoneNumber);
            map.put("delivery_id","JD");
            log.info("map请求参数---->{}",map);
            String doPost = HttpClientUtil.doPost("https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/trace_waybill", map, accessToken);
            JSONObject doPostObject = JSON.parseObject(doPost);
            // 从JSONObject中获取openid并返回
            String waybillToken = doPostObject.getString("waybill_token");
            log.info("waybillToken--->{}",waybillToken);
            return ResponseResult.success(waybillToken);
        }catch (BusinessException e) {
            return ResponseResult.failure(e.getCode(), e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
